package com.mundus.engine.assets.vertex;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL15;

public class VertexFactory <T extends Vertex>{
	private List<T> _vertices;
	private List<Byte> _indices;
	private T _currentObject;
	
	public List<T> getVerticesList() { return _vertices;}
	public Vertex[] getVerticesArray(){ return (Vertex[]) _vertices.toArray();}
	
	public List<Byte> getIndicesList(){ return _indices;}
	public byte[] getIndicesArray(){
		byte[] outArray = new byte[_indices.size()];
		for(int i = 0; i < outArray.length; i++)
			outArray[i] = _indices.get(i);
		
		return outArray;
	}
	
	public VertexFactory(T[] vertices){
		
		_vertices = new ArrayList<T>();
		_indices = new ArrayList<Byte>();
		
		for(T v : vertices)
			_vertices.add(v);
	}
	
	public VertexFactory(){
		_vertices = new ArrayList<T>();
		_indices = new ArrayList<Byte>();
	}
	
	public void addVertex(T vertex){
		_vertices.add(vertex);
	}
	
	public void addIndices(byte[] indices){
		for(int i = 0; i < indices.length; i++)
			_indices.add(indices[i]);
	}
	
	public VertexDrawable genVertexDrawable(){
		_currentObject = _vertices.get(0);
		
		byte[] passArray = new byte[_indices.size()];
		for(int i = 0; i < passArray.length; i++)
			passArray[i] = _indices.get(i);
		
		return new VertexDrawable(getVertexArrayObject(), getIndicesBufferObject(passArray),_currentObject);
	}
	
	public int getVertexArrayObject(){	
		
		Vertex[] passArray = new Vertex[_vertices.size()];
		for(int i = 0; i < passArray.length; i++)
			passArray[i] = (T)_vertices.get(i);
		
		return _currentObject.getVAO(passArray);
	}
	
	public int getIndicesBufferObject(byte[] indices){
		ByteBuffer indicesBuffer = BufferUtils.createByteBuffer(indices.length);
		indicesBuffer.put(indices);
		indicesBuffer.flip();
		
		int vboiId = GL15.glGenBuffers();
		GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboiId);
		GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL15.GL_STATIC_DRAW);
		GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
		
		return vboiId;
	}
	
}
